#include "Radar.h"
#include<iostream>

using namespace std;
using namespace bfs;

Radar::Radar()
{
	m_bCreate = false;
	m_sExtension = "";
	m_sIgnore = "";
}

int Radar::scan(string sSourceDir, bool bRecurse)
{
	m_xFileListRoot = complete(path(sSourceDir, native));
	m_xFileListRoot = system_complete(m_xFileListRoot);

	if( !exists(m_xFileListRoot) )
	{
		cerr<<m_xFileListRoot.leaf()<<" does not exist.\n";
		return 2;
	}

	if( !is_directory(m_xFileListRoot))
	{
		cerr<<m_xFileListRoot.leaf()<<" is not a directory.\n";
		return 3;
	}

	scanDirectory(m_xFileListRoot);
	return 0;
}

bool Radar::isFileTypeSupported(string sExtension)
{
	if(m_sExtension!="")
		return (m_sExtension==sExtension);

	return true;
}

bool Radar::isInIgnoreList(std::string sFilename)
{
	if(m_sIgnore!="")
		return (m_sIgnore == sFilename);
	return false;
}


void Radar::scanDirectory(const path& xPath, int nLevel, bool bRecurse)
{
	directory_iterator pxLooper(xPath); //VSExpress Intellisense has a problem with this
	directory_iterator pxLoopEnd;
	path xDirEntry;
	FileListItem* pxFileListItem = NULL;

	for(; pxLooper != pxLoopEnd; ++pxLooper)
	{
		xDirEntry = *pxLooper;

		try {
		if(isInIgnoreList(xDirEntry.filename()))
			continue;

		bool bIsDirectory = is_directory(xDirEntry);
		if(bIsDirectory)
		{
			if(bRecurse)
				scanDirectory(xDirEntry, nLevel, bRecurse);
		}
		else
			//For files
		{
			string sFileExtension = extension(xDirEntry);
			if (!isFileTypeSupported(sFileExtension))
				continue;

			pxFileListItem = new FileListItem;
			pxFileListItem->m_sName = xDirEntry.filename();
			pxFileListItem->m_nSize = file_size(xDirEntry);
			pxFileListItem->m_sLocation = xDirEntry.parent_path().string();
			pxFileListItem->m_sExtension = xDirEntry.extension();
			pxFileListItem->m_nLevel = nLevel;
			pxFileListItem->m_eType = bIsDirectory ? FileListItem::eDirectory : FileListItem::eFile;
			m_xFileList.m_apxItem.push_back(pxFileListItem);

		}

		} catch(const std::exception & ex) {
			std::cerr<<pxLooper->leaf() <<": " <<ex.what() <<std::endl;
		}
	}  //End of for()
}  

const FileList* Radar::getFileList()
{
	return &m_xFileList;
}

void Radar::dump()
{
	unsigned long nTotalSize;
	m_xFileList.dump(nTotalSize);
}






